<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon class="relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div class="absolute top-4px right-10px">
                <Tooltip title="删除">
                  <Button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </Button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #toolbar>
        <Dropdown
          :trigger="['click']"
          :dropMenuList="[
            {
              text: '添加资产配置',
              icon: ICON.ADDENTITY,
              event: '',
              onClick: () => {
                openModal(true, { key: 'add' });
              },
            },
            {
              text: '导入资产配置',
              icon: ICON.IMPORTENTITY,
              event: '',
              onClick: () => {
                openModal(true, { key: 'import' });
              },
            },
          ]"
        >
          <Button type="primary">添加资产配置</Button>
        </Dropdown>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: ICON.EDIT,
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: openEditModal.bind(null, true, { record }),
              },
              {
                icon: ICON.CHECK,
                tooltip: {
                  title: '详情',
                  placement: 'top',
                },
                onClick: handleDetail.bind(null, record),
              },
              {
                icon: ICON.DELETE,
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                onClick: handleDelete.bind(null, record),
                disabled: record.default,
              },
            ]"
            :dropDownActions="[
              {
                icon: ICON.EXPORT,
                label: '导出资产配置',
                onClick: exportJson.bind(null, record),
              },
              {
                icon: ICON.FLAG,
                label: '设为默认资产配置',
                disabled: record.default,
                onClick: handleDefault.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AddModel @register="registerModal" @add="addProfiles" />
    <PublicDrawer
      @register="registerDrawer"
      :showTabs="['detail', 'auditLogs', 'version']"
      @update-desc-data="handleUpdateDescData" />
    <EditFilesModal @register="registerEditModal" @edit="editOk"
  /></div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { getBasicColumns, searchSchema } from './data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import Icon from '/@/components/Icon';
  import { ICON } from '/@/enums/iconEnum';
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import { Dropdown } from '/@/components/Dropdown';
  import { Alert, Tooltip, Button } from 'ant-design-vue';
  import AddModel from './components/AddModel.vue';
  import { DescriptionSchema } from './components/detailDescription.data';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import EditFilesModal from './components/EditAssetFilesModal.vue';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { assetProfileParams } from '/@/api/thingsborad/profile/assetProfile/model/assetProfileModel';
  import {
    getAssetProfileTableList,
    setAssetProfileDefault,
    deleteAssetProfile,
    getAssetProfileById,
    getRuleChainItem,
    getDashBoardItem,
  } from '/@/api/thingsborad/profile/assetProfile/assetProfile';
  import dayjs from 'dayjs';
  import { saveAs } from 'file-saver';
  import { ref } from 'vue';
  const checkedKeys = ref<any>([]);
  const { createConfirm } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerEditModal, { openModal: openEditModal }] = useModal();
  const [registerTable, { reload, setProps }] = useTable({
    title: '资产配置',
    columns: getBasicColumns,
    api: getAssetProfileTableList,
    ...tableStyleSetting,
    beforeFetch: (val) => {
      if (!val.field) {
        (val.field = 'createdTime'), (val.order = 'DESC');
      }
      let params: assetProfileParams = {
        page: val.page - 1,
        pageSize: val.pageSize,
        sortOrder: val.order === 'ascend' ? 'ASC' : 'DESC',
        sortProperty: val.field === 'default' ? 'isDefault' : val.field,
      };
      val?.textSearch ? (params.textSearch = val.textSearch) : null;
      return params;
    },
    afterFetch: (res) => {
      let list: Recordable[] = [];
      res.length != 0
        ? res.forEach((item: Recordable) => {
            item.createdTime = dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss');
            item.id = item.id.id;
            list.push(item);
          })
        : null;
      return list;
    },
    formConfig: {
      layout: 'horizontal',
      schemas: searchSchema,
      showAdvancedButton: false,
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 8 },
        lg: { span: 6, offset: 12 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
      submitFunc: async () => {
        reload();
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
      getCheckboxProps: (record) => ({
        disabled: record.default,
      }),
    },
  });
  // 多选
  function onSelect(record: Recordable, selected: boolean) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id: string) => id !== record.id);
    }
  }
  function onSelectAll(selected: boolean, _selectedRows: Recordable[], changeRows: Recordable[]) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  //多选删除
  function handleSelectedDelete() {
    createConfirm({
      iconType: 'info',
      title: `确定要删除${checkedKeys.value.length}个资产配置吗？`,
      content: '请注意：确认后，资产配置及其所有相关数据将不可恢复。',
      onOk: async () => {
        setProps({ loading: true });
        for (const item of checkedKeys.value) {
          let paramsURL = '/' + item;
          try {
            await deleteAssetProfile(paramsURL);
            reload();
          } catch (error) {
            console.error('删除失败', error);
          }
        }
        checkedKeys.value = [];
      },
    });
  }
  function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要删除${record.name}设备配置吗？`,
      content: '请注意：确认后，设备及其所有相关数据将不可恢复。',
      onOk: async () => {
        let paramsURL = '/' + record.id;
        try {
          await deleteAssetProfile(paramsURL);
          reload();
        } catch (error) {
          console.error('删除失败', error);
        }
      },
    });
  }

  function handleDefault(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要将设备配置${record.name}设为默认值吗？`,
      content: '确认后，设备配置将被标记为默认，并将用于未指定配置的新设备。',
      onOk: () => {
        setItemDefault(record);
      },
    });
  }
  // 设置默认
  async function setItemDefault(record: Recordable) {
    let paramsURL = '/' + record.id + '/default';
    try {
      await setAssetProfileDefault(paramsURL);
      reload({
        sortInfo: { field: 'isDefault', order: 'ASC' },
      });
    } catch (error) {
      console.error('设置为默认出错', error);
    }
  }

  const [registerDrawer, { openDrawer }] = useDrawer();

  function handleDetail(record: Recordable) {
    openDrawer(true, {
      entityType: ENTITY_TYPE.ASSET_PROFILE,
      entityId: record.id,
      title: record.name,
      api: getAssetProfileById,
      detailSchema: DescriptionSchema,
      params: '/' + record.id,
    });
  }

  function handleUpdateDescData(value: Recordable) {
    if (value.defaultRuleChainId) {
      let paramsURL = '/' + value.defaultRuleChainId.id;
      try {
        getRuleChainItem(paramsURL).then((res: Recordable) => {
          value.defaultRuleChain = res.name;
        });
      } catch (error) {
        console.error('获取规则链信息出错', error);
      }
    } else {
      value.defaultRuleChain = null;
    }
    if (value.defaultDashboardId) {
      let paramsURL = '/' + value.defaultDashboardId.id;
      try {
        getDashBoardItem(paramsURL).then((res: Recordable) => {
          value.defaultDashboard = res.name;
        });
      } catch (error) {
        console.error('获取移动仪表盘出错', error);
      }
    } else {
      value.defaultDashboard = null;
    }
    if (value.defaultEdgeRuleChainId) {
      let paramsURL = '/' + value.defaultEdgeRuleChainId.id;
      try {
        getRuleChainItem(paramsURL).then((res: Recordable) => {
          value.defaultEdgeRuleChain = res.name;
        });
      } catch (error) {
        console.error('获取规则链信息出错', error);
      }
    } else {
      value.defaultEdgeRuleChain = null;
    }
  }
  //导出json文件
  async function exportJson(record: Recordable) {
    let params = '/' + record.id;
    try {
      getAssetProfileById(params).then((jsonData: Recordable) => {
        delete jsonData.id;
        delete jsonData.createdTime;
        delete jsonData.tenantId;
        const jsonBlob = new Blob([JSON.stringify(jsonData, null, 2)], {
          type: 'application/json',
        });
        saveAs(jsonBlob, `${record.name}.json`); // 使用file-saver的saveAs方法下载文件
      });
    } catch (error) {}
  }
  function addProfiles() {
    reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
  }

  function editOk() {
    reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
  }
</script>
